<?php

$image = $_GET["image"];
$w = $_GET["w"];
$h = $_GET["h"];
if($image){
	Image::img_show($image, $w, $h);
}

class Image{

	public static function img_show($path,$w=null,$h=null){
		$img = self::img_create($path);
		if($w || $h){
			self::img_resize($img, $w, $h);
		}
		self::img_throw($img, substr($path, strrpos($path, "/"), strrpos($path, ".")));
	}

	public static function img_create($path){
		$ext = strtolower(substr($path, strrpos($path, ".")+1));
		$img = false;

		switch($ext){
			case "jpg":
			case "jpeg":
				$img = imagecreatefromjpeg($path);
				break;
			case "gif":
				$img = imagecreatefromgif($path);
				break;
			case "png":
				$img = imagecreatefrompng($path);
				break;
		}

		if(!$img){
			die("Error creating image.");
		}

		return $img;
	}

	public static function img_throw($img, $name){
		$ext = strtolower(substr($name, strrpos($name, ".")+1));

		header("Content-Type: image/$ext");
		header("Content-Disposition: inline; filename=$name");
		switch($ext){
			case "jpg":
			case "jpeg":
				imagejpeg($img);
				break;
			case "gif":
				imagegif($img);
				break;
			case "png":
				imagepng($img);
				break;
		}
	}

	public static function img_resize(&$img, $w=null, $h=null){
		$w1 = imagesx($img);
		$h1 = imagesy($img);

		if($w && $w1 > $w){
			$h1 = $w/$w1*$h1;
			$w1 = $w;
		}
		if($h && $h1 > $h){
			$w1 = $h/$h1*$w1;
			$h1 = $h;
		}

		$img2 = imagecreatetruecolor($w1,$h1);
		imagecopyresized($img2, $img, 0, 0, 0, 0, $w1, $h1, imagesx($img), imagesy($img));
		$img = $img2;
	}
}